<!-- eslint-disable no-undef -->
<template>
  <div class="attendclass_talk">
    <!-- 如果图片被放大，显示放大后的图片 -->
    <div
      v-if="isEnlarged"
      class="enlarged-image-overlays"
      @click="closeEnlargedImage"
    >
      <img :src="imageUrl" class="enlarged-image" />
      <i class="el-icon-close gba"></i>
    </div>
    <i class="el-icon-close syfkclose" @click="closeTalk"></i>
    <div
      class="attendclass_talk_cont beautifulScroll"
      id="sectionmain"
      ref="sectionmain"
    >
      <div
        class="course_chatItem clearfix"
        :class="item.mine ? 'isMine' : 'isnotMine'"
        v-for="(item, index) in hisMessageList"
        :key="index"
      >
        <div class="course_chatIcon">
          <img
            :src="item.avatar"
            v-if="item.avatar"
            v-img-error="handleImageError"
          />
          <img src="@/images/user_infoicon.png" v-else />
        </div>
        <div class="course_chatInfo">
          <span>{{ item.username }}</span>
          <!-- <span class="course_chatInfolabel" v-if="item.mine">我</span> -->
          <span>{{ item.timestamp }}</span>
        </div>
        <div
          class="course_chatText"
          v-html="item.content"
          @click="enlargeImage(item.content)"
          ref="dynamicImage"
        ></div>
      </div>
      <div
        class="info_cancel"
        v-if="hisMessageList && hisMessageList.length > 0"
      >
        以上是历史消息
      </div>
      <div
        class="course_chatItem clearfix"
        :class="item.mine ? 'isMine' : 'isnotMine'"
        v-for="(item, index) in messageList"
        :key="'fltum' + index"
      >
        <div class="course_chatIcon">
          <img :src="item.avatar" v-if="item.avatar" />
          <img src="@/images/user_infoicon.png" v-else />
        </div>
        <div class="course_chatInfo">
          <span>{{ item.username }}</span>
          <!-- <span class="course_chatInfolabel" v-if="item.mine">我</span> -->
          <span>{{ item.timestamp }}</span>
        </div>
        <div
          class="course_chatText"
          v-html="item.content"
          @click="enlargeImage(item.content)"
          ref="dynamicImage"
        ></div>
      </div>
    </div>
    <div class="attendclass_talk_stand"></div>
    <div class="attendclass_talk_input">
      <textarea
        class="beautifulScroll"
        v-model="messageContent"
        @keyup.enter="checkMessage"
        placeholder="您好，我的回答？"
      ></textarea>

      <!-- <el-input
        type="textarea"
        class="beautifulScroll"
        @keyup.enter="checkMessage"
        placeholder="您好，我的回答？"
        v-model="messageContent"
        @input="checkEnter"
      >
      </el-input> -->
      <div class="attendclass_talk_btn like_btn" @click="checkMessage">
        发送
      </div>
    </div>
  </div>
</template>

<script>
import RequestUtils from '@/utils/RequestUtils'
import {
  logout,
  imageLoad,
  ChatListUtils,
  MessageTargetType
} from '@/utils/ChatUtils'
import { parseTime } from '@/filters/indexs.js'

import { imInit, imMessageList } from '@/api/imuser.js'
// import { getInfo } from '@/api/user.js'
export default {
  props: {
    classroomId: {
      required: false,
      default: ''
    }
  },
  computed: {
    messageList: {
      get: function() {
        return this.$store.state.im.messageList
      },
      set: function(messageList) {
        this.$store.commit('setMessageList', messageList)
      }
    },
    currentChat: {
      get: function() {
        return this.$store.state.im.currentChat
      },
      set: function(currentChat) {
        this.$store.commit(
          'setCurrentChat',
          JSON.parse(JSON.stringify(currentChat))
        )
      }
    }
  },
  data() {
    return {
      isEnlarged: false,
      userinfo: {
        userId: '1',
        name: '技术人员'
      },
      //聊天
      chat: {},
      pageNum: 1,
      pageSize: 20,
      total: -1,
      messageContent: '',
      userList: [],
      hisMessageList: []
    }
  },
  created() {
    // this.getInfo()
    this.getInit()
  },
  watch: {
    classroomId: {
      handler(i) {
        console.log(i)
        this.getHistory()
        this.currentChat.id = i
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {},
  methods: {
    closeEnlargedImage() {
      // 关闭放大的图片
      this.isEnlarged = false
    },
    enlargeImage(str) {
      // 使用正则表达式匹配 src 属性的值
      const srcRegex = /src="(.*?)"/
      const matches = str.match(srcRegex)

      // 如果匹配成功，matches[1] 就是 src 属性的值
      if (matches && matches.length > 1) {
        const src = matches[1]
        this.imageUrl = src
        console.log('图片地址', src) // 输出图片的地址
        this.isEnlarged = true
        console.log('点击了图片放大')
      } else {
        console.log('未找到 src 属性')
      }
    },
    checkEnter(event) {
      console.log(event.keyCode)
      // 检测是否按下回车键 (Enter key code is 13)
      if (event.keyCode === 13) {
        console.log('回车')
        // 阻止默认行为，防止回车键换行
        event.preventDefault()
        // 发送消息
        this.checkMessage()
      }
    },
    handleImageError(event) {
      // console.error('图片加载失败:', event)

      // 替换为默认图片
      event.target.src = require('@/images/user_infoicon.png') // 替换为你的默认图片路径
    },
    // 获取用户信息
    getInfo() {
      getInfo().then(res => {
        this.userinfo = res.data
        console.log('用户信息', res.data)
        this.getInit()
      })
    },
    getInit() {
      this.init()
      this.$store.commit('setUser', this.userinfo)
      // imInit().then((res) => {
      //   //个人信息
      //   this.$store.commit('setUser', res.data.me)
      //   //好友
      //   this.$store.commit('setUserFriendList', res.data.friends)
      //   //群
      //   let chatMap = new Map()
      //   var groups = res.data.groups
      //   groups.map((group) => {
      //     chatMap.set(group.id, group)
      //   })
      //   this.$store.commit('setChatGroupList', groups)
      //   this.$store.commit('setChatMap', chatMap)

      //   this.$nextTick(() => {
      //     // this.init()
      //   })
      // })
    },
    init() {
      console.log('初始化websoket成功')
      this.chat = {
        id: this.classroomId, //实验id 房间id 现在用用户id来判断
        type: MessageTargetType.FRIEND
        // MessageTargetType.CHAT_GROUP 群聊
      }
      RequestUtils.getInstance().webSocketOperation(this)
      //
      ChatListUtils.resetChatList(
        // 设置默认写死的系统管理员
        this,
        {
          userId: this.userinfo.userId,
          name: this.userinfo.name
        },
        // MessageTargetType.CHAT_GROUP 群聊
        MessageTargetType.FRIEND //私聊
      )
      this.initIm()
      this.getHistory()
      this.scrollMain()
    },
    initIm() {
      this.$store.commit('resetUnRead')
      this.$store.commit('setCurrentChat', this.chat)
      this.$store.commit(
        'setChatList',
        ChatListUtils.getChatList(this.userinfo.userId)
      )
      this.messageList = []
      // 从内存中取聊天信息
      let cacheMessages = this.$store.state.im.messageListMap[this.classroomId]
      if (cacheMessages) {
        this.messageList = cacheMessages
      }
      let currentChat = this.$store.state.im.currentChat
      if (currentChat) {
        this.currentChat = currentChat
      }
      // 每次滚动到最底部
      this.$nextTick(() => {
        imageLoad('sectionmain')
      })
      // 群组的聊天
      // if (this.chat.type === '1') {
      //   imChatUserList({
      //     chatId: this.classroomId,
      //   }).then((res) => {
      //     this.userList = res.data
      //   })
      // }
    },
    checkMessage() {
      let time = new Date().getTime()
      let content = this.messageContent
      if (content !== '' && content !== '\n') {
        if (content.length > 2000) {
          this.openMessage('不能超过2000个字符')
        } else {
          let currentMessage = {
            mine: true,
            avatar: this.userinfo.iconurl,
            username: this.userinfo.name,
            fromId: this.userinfo.userId,
            chatId: this.classroomId,
            id: this.classroomId,
            type: this.chat.type,
            timestamp: time,
            content: content
          }
          this.sendTimMessage(currentMessage)
        }
      }
    },
    sendTimMessage(message) {
      this.$store.commit('sendMessage', message)
      message.timestamp = parseTime(
        new Date(message.timestamp),
        '{y}-{m}-{d} {h}:{i}:{s}'
      )
      this.$store.commit('addMessage', message)
      this.messageContent = ''
      // 每次滚动到最底部
      this.$nextTick(() => {
        imageLoad('sectionmain')
      })
    },
    scrollMain() {
      console.log('执行了滚动到底部')
      var that = this

      $('#sectionmain').scroll(function() {
        var scrollTop = $('#sectionmain')[0].scrollTop
        if (scrollTop == 0) {
          that.getHistory()
        }
      })
    },
    // 获取聊天记录
    getHistory() {
      this.hisMessageList = []
      var that = this
      if (this.hisMessageList.length == 0) {
        imMessageList({
          chatId: this.classroomId, //接受人id 用户id 测试使用id
          fromId: 1 //发送人id 默认传超级管理员
        }).then(res => {
          let list = res.data
          let tempList = list.map(function(message) {
            message.timestamp = parseTime(
              new Date(message.timestamp),
              '{y}-{m}-{d} {h}:{i}:{s}'
            )

            return message
          })
          this.$nextTick(() => {
            imageLoad('sectionmain')
          })
          this.hisMessageList = tempList.reverse().concat(that.hisMessageList)
          console.log(this.hisMessageList)
          this.total = res.data.total
          this.pageNum++
        })
      }
    },
    closeTalk() {
      this.$emit('closeTalk')
      this.$emit('classroomIdfns', this.classroomId)
    }
  },
  beforeDestroy() {
    try {
      logout(this) //断开聊天socket
    } catch (err) {}
  }
}
</script>
<style>
.attendclass_detail_lefttopback {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 22px;
  overflow: hidden;
}

.attendclass_detail_lefttopinfo {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 22px;
  text-align: center;
}

.attendclass_detail_toptab {
  width: 108px;
  height: 38px;
  display: inline-block;
  cursor: pointer;
  margin: 0 4px;
  position: relative;
  top: -24px;
  border-radius: 8px 8px 0 0;
  text-align: center;
  line-height: 38px;
  background: linear-gradient(
    to bottom,
    rgb(172, 212, 213),
    rgb(145, 145, 145)
  );
  font-size: 16px;
  font-family: pingfang;
  font-weight: 600;
  color: #303a40;
  letter-spacing: 2px;
}

.attendclass_detail_toptab img {
  position: relative;
  top: 6px;
}

.attendclass_detail_toptab:hover,
.attendclass_detail_toptab.active {
  background: linear-gradient(to right, #1d8486, #3e9151);
  color: #ffffff;
}

.attendclass_detail_leftbottom {
  width: 100%;
  height: calc(100% - 22px);
}

.attendclass_left_list {
  height: calc(100% - 84px);
  padding: 0;
}

.attendclass_left_add {
  width: 100%;
  height: 28px;
  text-align: center;
  margin: 0 0 12px 0;
}

.attendclass_left_addbtn {
  width: 115px;
  height: 28px;
  text-align: center;
  line-height: 28px;
  font-size: 14px;
  font-family: pingfang;
  font-weight: 400;
  color: #dfd9bd;
  background: #1d8486;
  margin: 0 auto;
  border-radius: 4px;
}

.attendclass_left_item {
  width: 100%;
  height: 40px;
  box-sizing: border-box;
  border-bottom: 1px dashed #707070;
  padding: 8px 30px 0 16px;
  position: relative;
}

.attendclass_left_itemin {
  width: 100%;
  height: 22px;
  cursor: pointer;
  line-height: 22px;
  font-size: 14px;
  font-family: pingfang;
  font-weight: 400;
  color: #d5dfe1;
  position: relative;
}

.attendclass_left_itemin img {
  float: left;
  margin: 3px 6px 0 4px;
  height: 16px;
}

.attendclass_left_itemin.active {
  background: #84861d;
  color: #ffffff;
}

.attendclass_left_itemdelete {
  position: absolute;
  right: 0;
  height: 40px;
  text-align: center;
  width: 30px;
  font-size: 16px;
  top: 0;
  color: #adb9bb;
  display: none;
  line-height: 40px;
}

.attendclass_left_item:hover .attendclass_left_itemdelete {
  display: block;
}

.attendclass_detail_right {
  float: left;
  width: calc(100% - 740px);
  height: calc(100% - 42px);
  margin: 12px 0 0 0;
  position: relative;
  z-index: 1;
  transition: width 0.3s;
}

.attendclass_detail_right.active {
  width: calc(100% - 500px);
}

.attendclass_detail_righttabs {
  height: 58px;
  width: 100%;
}

.attendclass_detail_righttab {
  width: auto;
  height: 58px;
  margin: 0 8px 0 0;
  float: left;
}

.attendclass_detail_main {
  width: 100%;
  height: calc(100% - 58px);
  position: relative;
}

.attendclass_detail_opentask {
  position: absolute;
  right: 10px;
  bottom: 75px;
  z-index: 1;
}

.attendclass_talk {
  width: 505px;
  height: 900px;
  position: fixed;
  right: 0;
  top: 5px;
  bottom: 0px;
  background: #ffffff;
  box-shadow: 4px 4px 46px 0px rgba(0, 0, 0, 0.25);
  z-index: 9;
}

.attendclass_talk_close {
  position: absolute;
  right: 14px;
  top: 10px;
}

.attendclass_talk_cont {
  background: #ffffff;
  width: 100%;
  height: calc(100% - 260px);
  overflow-y: auto;
  margin: 35px 0 0 0;
  position: relative;
  z-index: 1;
  box-sizing: border-box;
  padding: 20px;
}

.attendclass_talk_stand {
  padding-left: 15px;
  line-height: 40px;
  width: 100%;
  height: 40px;
  background: #eff3f6;
}

.attendclass_talk_input {
  width: 100%;
  height: 185px;
}

.attendclass_talk_input textarea {
  font-family: pingfang;
  width: 100%;
  height: 100%;
  line-height: 30px;
  font-size: 15px;
  color: #ffffff;
  box-sizing: border-box;
  background: transparent;
  padding: 0 5px 0 12px;
  resize: none;
  border: 1px solid #ffffff;
}
/* 修改 focus-visible 的样式 */
.attendclass_talk_input textarea:focus-visible {
  outline: none; /* 修改焦点时的描边颜色 */
  /* 添加其他需要的样式 */
}

/* 其他浏览器前缀 */
.attendclass_talk_input textarea::-webkit-focus-visible {
  outline: none;
}

.attendclass_talk_input .el-textarea__inner:hover {
  border: none;
}
.attendclass_talk_input .el-textarea__inner {
  width: 505px;
  height: 185px;
}
.attendclass_talk_btn {
  width: 69px;
  height: 32px;
  background: #3576ff;
  text-align: center;
  line-height: 32px;
  font-size: 14px;
  font-family: pingfang;
  font-weight: 400;
  color: #ffffff;
  position: absolute;
  right: 10px;
  bottom: 10px;
  border-radius: 3px;
}

.course_chatItem {
  height: auto;
  width: 100%;
  box-sizing: border-box;
  padding: 20px 45px 15px 45px;
  position: relative;
  margin: 0 0 15px 0;
}

.course_chatIcon {
  width: 35px;
  height: 35px;
  position: absolute;
  top: 0;
  border-radius: 50%;
  overflow: hidden;
}

.course_chatIcon img {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  height: auto;
  min-height: 100%;
}

.course_chatInfo {
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  font-weight: 400;
  color: #939393;
  position: absolute;
  top: -10px;
}

.course_chatText {
  display: inline-block;
  width: auto;
  max-width: 100%;
  height: auto;
  box-sizing: border-box;
  padding: 10px 16px;
  font-size: 15px;
  font-weight: 400;
  line-height: 30px;
  color: #717798;
  background: #eff3f6;
  border: 1px solid #eff3f6;
  border-radius: 6px;
}

.course_chatItem.isnotMine .course_chatIcon {
  left: 0;
}

.course_chatItem.isMine .course_chatIcon {
  right: 0;
}

.course_chatItem.isnotMine .course_chatInfo {
  text-align: left;
  left: 45px;
}

.course_chatItem.isMine .course_chatInfo {
  text-align: right;
  right: 45px;
}

.course_chatItem.isnotMine .course_chatInfo span {
  margin: 0 20px 0 0;
}

.course_chatItem.isMine .course_chatInfo span {
  margin: 0 0 0 20px;
}

.course_chatInfolabel {
  display: inline-block;
  width: auto;
  height: 16px;
  line-height: 16px;
  padding: 0 8px;
  font-size: 12px;
  font-family: pingfang;
  font-weight: 400;
  color: #dfd9bd;
  background: linear-gradient(to right, #1d8486, #3e9151);
  border-radius: 8px;
  margin-top: 7px !important;
}

.course_chatItem.isnotMine .course_chatText {
  float: left;
}

.course_chatItem.isMine .course_chatText {
  float: right;
}

.course_chatItem.isMine .course_chatInfo span {
  float: right;
}
.like_btn {
  cursor: pointer;
}
.attendclass_talk_input textarea {
  color: #717798;
}
.info_cancel {
  color: #717798;
  margin: 15px 0;
}
.attendclass_talk_input .input-box {
  height: 184px !important;
  width: 505px;
  border-radius: 0px !important;
}
.syfkclose {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 24px;
  cursor: pointer;
}
.enlarged-image-overlays {
  cursor: pointer;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999999;
}
</style>
